package com.codeoss.framework.expression;

import java.util.Map;

import javax.script.Bindings;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.codeoss.framework.context.UserContext;


@Component("javascriptScriptService")
public class JavaScriptScriptService implements IScriptService,ApplicationContextAware {
	private static ScriptEngine  engine;
	static{
		ScriptEngineManager   manager=new ScriptEngineManager();
		engine=manager.getEngineByName("JavaScript");
	}
	
	private ApplicationContext applicationContext;
	@Override
	public <T extends Object> T eval(String script,Map<String,Object> bindingMap) {
		// TODO Auto-generated method stub
		try {
			Bindings bindings=engine.createBindings();
    		if(bindingMap!=null){
    			bindings.putAll(bindingMap);
    		}
    		String beanNames[]=applicationContext.getBeanDefinitionNames();
    		for (int i = 0; i < beanNames.length; i++) {
    			if(!beanNames[i].equals("ureport.props")) {
    				bindings.put(beanNames[i], applicationContext.getBean(beanNames[i]));
    			}
			}
    		//Map<String,Object> userContextMap=UserContext.getCurrentUserContext().getUserContextMap();
    		//bindings.putAll(userContextMap);
    		bindings.put("userContext", UserContext.getCurrentUserContext());
			return (T)engine.eval(script,bindings);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw new ScriptEvalException(script,e);
		}
	}
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		// TODO Auto-generated method stub
		this.applicationContext=applicationContext;
	}
}
